/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tesam.gedeon.controller;

import com.tesam.gedeon.entity.SystemUser;
import com.tesam.gedeon.service.SystemUserService;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author joelpacheco
 */
@Controller("SystemUserController")
@SessionAttributes("sessionId")
public class SystemUserController {

    @Autowired
    private SystemUserService User;
    private HttpSession newSesion;
    Cookie locationCookie;

    @RequestMapping(value = "/sidebar_search")
    public ModelAndView sidebar_search(@ModelAttribute("systemUser") SystemUser user , HttpServletRequest request ){
        ModelAndView mv = new ModelAndView("/sidebar_search") ; 
        mv.addObject("moduleData", User.getSearchModuleData(user));
        mv.addObject("dataModule", User.getModuleSearch(user));
        mv.addObject("dataPatenTab", User.getParentTabSearch(user));
        return mv ;
    }
    
    @RequestMapping(value = "/")
    public ModelAndView index(@ModelAttribute("systemUser") SystemUser user,
            SessionStatus status,
            HttpServletRequest request,
            HttpServletResponse response) {
        System.out.println("esta aki");
        HttpSession newSesion;
        newSesion = request.getSession(false);

        if (newSesion != null) {

            if (newSesion.getAttribute("sessionId") != null) {

                if (!newSesion.getAttribute("sessionId").equals("")) {

                    user.setSessionId(newSesion.getAttribute("sessionId").toString());

                }
            }
        }

        String goPage = "/home";
        String sessionId = "";

        ModelAndView mv = new ModelAndView(goPage);

        if (user.getSessionId() != null) {

            if (!user.getSessionId().equals("")) {

                List<SystemUser> result = getDataSystem(request);

                if (result.size() == 0) {

                    goPage = "/login/index";

                    mv = new ModelAndView(goPage);
                } else if (result.size() > 0) {

                    goPage = "/home";

                    sessionId = result.get(0).getSessionId();

                    user.setSessionId(sessionId);

                    mv = new ModelAndView(goPage);

                    mv.addObject("module", "0");

                    this.loadDataSystem(mv, request);

                } else {
                    goPage = "/login/index";

                    mv = new ModelAndView(goPage);
                }

            } else {
                goPage = "/login/index";
                mv = new ModelAndView(goPage);
            }

        } else {

            goPage = "/login/index";

            mv = new ModelAndView(goPage);

        }

        if (request.getParameter("closedSession") != null) {
            if (request.getParameter("closedSession").toString().equals("1")) {;
                mv.addObject("closedSession", request.getParameter("closedSession"));
            }
        }

        return mv;

    }

    public List<SystemUser> getDataSystem(HttpServletRequest request) {

        HttpSession newSesion = request.getSession(false);

        SystemUser user = new SystemUser();

        if (newSesion != null) {

            if (newSesion.getAttribute("sessionId") != null) {

                if (!newSesion.getAttribute("sessionId").equals("")) {

                    user.setSessionId(newSesion.getAttribute("sessionId").toString());

                }

            }

        }

        List<SystemUser> result = User.getSession(user);

        User.updateSession(user);

        return result;

    }

    public List<SystemUser> getDataModule(HttpServletRequest request) {

        SystemUser user = new SystemUser();

        List<SystemUser> result = User.getModule(user);

        return result;
    }

    public List<SystemUser> getDataParentTab() {
        return User.getParentTab();
    }

    public List<SystemUser> getModuleData(HttpServletRequest request) {
        SystemUser user = new SystemUser();

        int id = 0;

        if (request.getParameter("module") != null && !request.getParameter("module").equals("")) {
            id = Integer.parseInt(request.getParameter("module").toString());
            request.getSession().removeAttribute("module");
            request.getSession().setAttribute("module", id);
        } else {
            if (request.getSession().getAttribute("module") != null) {
                id = Integer.parseInt(request.getSession().getAttribute("module").toString());
            }
        }
        user.setId(id);

        return User.getModuleData(user);
    }

    public void loadDataSystem(ModelAndView mv, HttpServletRequest request) {
        mv.addObject("dataModule", this.getDataModule(request));
        mv.addObject("dataPatenTab", this.getDataParentTab());
        mv.addObject("dataSystem", this.getDataSystem(request));
        mv.addObject("moduleData", this.getModuleData(request));
    }

    @RequestMapping(value = "/login/login", method = RequestMethod.POST)
    public ModelAndView Login(@ModelAttribute("systemUser") SystemUser user,
            SessionStatus status,
            HttpServletRequest request,
            HttpServletResponse response) {

        String goPage = "/login/index";
        String returnPage = "/login/home" ;
        if(request.getParameter("pagereturn") != null){
            if(!request.getParameter("pagereturn").toString().equals("")){
                returnPage = request.getParameter("pagereturn").toString() ;
            }
        }
        

        ModelAndView mv = new ModelAndView(goPage);
        String error = "" ;

        List<SystemUser> resultSession = User.getSession(user);
        if (resultSession.isEmpty()) {//no se ha logeado nunca

            if (user.getUserName().equals("") || user.getUserName().equals("")) {//sin usuario y clave

                goPage = returnPage;
                error = "2";
            } else {//ingreso usuario y clave

                List<SystemUser> result = User.login(user);//datos del login


                if (result.isEmpty()) {  //no hay datos
                    goPage = returnPage; 
                    error = "1";

                } else { //si hay datos

                    mv.addObject("dataSystem", result);

                    goPage = "/home2";

                }

                mv = new ModelAndView(goPage);
            }

        } else {//ya se logeo


            newSesion = request.getSession(true);

            goPage = "/home";

            mv = new ModelAndView(goPage);

        }
        mv.addObject("sessionId", user.getSessionId());

        if (request.getParameter("closedSession") != null) {
            if (request.getParameter("closedSession").toString().equals("1")) {;
                mv.addObject("closedSession", request.getParameter("closedSession"));
            }
        }
        mv.addObject("error", error);
        return mv;

    }

    @RequestMapping(value = "/login/logout")
    public ModelAndView logout(@ModelAttribute("systemUser") SystemUser user,
            SessionStatus status,
            HttpServletRequest request) throws ServletException {

        ModelAndView mv = new ModelAndView("/login/logout");

        HttpSession newSesion;
        newSesion = request.getSession(false);

        if (newSesion != null) {

            if (newSesion.getAttribute("sessionId") != null) {

                if (!newSesion.getAttribute("sessionId").equals("")) {

                    user.setSessionId(newSesion.getAttribute("sessionId").toString());

                }

            }

        }

        User.updateSession(user);

        User.logout(user);

        return mv;
    }

    @RequestMapping(value = "/login/logout2", method = RequestMethod.GET)
    public ModelAndView logout2(@ModelAttribute("systemUser") SystemUser user,
            SessionStatus status,
            HttpServletRequest request) {

        ModelAndView mv = new ModelAndView("/login/home");

        return mv;


    }

    @RequestMapping(value = "/login/home")
    public ModelAndView loginLogin(@ModelAttribute("systemUser") SystemUser user,
            SessionStatus status,
            HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("/login/home");

        return mv;
    }

    @RequestMapping(value = "/login/cookie")
    public ModelAndView loginCookie(@ModelAttribute("systemUser") SystemUser user,
            SessionStatus status,
            HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("/login/cookie");

        if (request.getParameter("s") != null) {
            user.setSessionId(request.getParameter("s").toString());

            List<SystemUser> result = User.getSession(user);

            if (result.isEmpty()) {
                mv = new ModelAndView("/login/reset");
                System.out.println("empty : " + user.getSessionId());
            } else {

                mv.addObject("user", result.get(0).getUserName());
                mv.addObject("valCookie", request.getParameter("s"));
                System.out.println("lleno : " + user.getSessionId());
            }
            mv.addObject("systemUser", result);
        } else {
            mv = new ModelAndView("/login/reset");
        }


        return mv;
    }

    @RequestMapping(value = "/login/byCookie")
    public ModelAndView loginByCookie(@ModelAttribute("systemUser") SystemUser user,
            SessionStatus status, HttpServletRequest request) {

        ModelAndView mv = new ModelAndView("/login/goHome");

        user.setSessionId(request.getParameter("sessionCookie").toString());

        List<SystemUser> result = User.getSession(user);

        User.logout(user);

        if (result.isEmpty()) {
            mv = new ModelAndView("/login/index");
        } else {
            user.setSessionId(request.getParameter("sessionId").toString());
            user.setIpComputer(request.getParameter("ipComputer").toString());
            result = User.LoginByCookie(user);

            if (result.isEmpty()) {
                mv = new ModelAndView("/login/index");
            } else {
                mv.addObject("sessionId", request.getParameter("sessionId").toString());
                this.loadDataSystem(mv, request);
                mv.addObject("module", "0");
                mv.addObject("loginByCookie", "si");
            }
        }

        return mv;
    }
    
    @RequestMapping(value = "/login/lockscreen")
    public ModelAndView lockscreen(@ModelAttribute("systemUser") SystemUser user , HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/login/lockscreen");
        
        mv.addObject("dataSystem", this.getDataSystem(request));
        if(request.getParameter("sessionId") != null){
            user.setSessionId(request.getParameter("sessionId").toString());
            System.out.println("sessionId : "+user.getSessionId());
        }
         
        User.updateSession(user);

        User.logout(user);
        
        return mv;
    }

    @RequestMapping(value = "/login/loginByAjax")
    public ModelAndView loginByLockScreen(@ModelAttribute("systemUser") SystemUser user, HttpServletRequest request ){
        ModelAndView mv = new ModelAndView("/login/resultByAjax");
        System.out.println("entro : ");
        mv.addObject("login", User.login(user).size());
         
        return mv;
    }
    
}




